package com.tqjc.system.core.websocket;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.tqjc.system.common.constant.ConfigConstant;
import com.tqjc.system.common.constant.GlobalConstant;
import com.tqjc.system.common.constant.RemoteURLConstant;
import com.tqjc.system.common.constant.SQLConstant;
import com.tqjc.system.common.entity.BO.CarExecuteInfoBO;
import com.tqjc.system.common.entity.BO.ResponseLabelDataBO;
import com.tqjc.system.common.entity.VO.CarExecuteInfoVO;
import com.tqjc.system.common.enums.CarInfoVOEnum;
import com.tqjc.system.common.enums.TankCarNoEnum;
import com.tqjc.system.common.enums.TaskStatusEnum;
import com.tqjc.system.core.config.WebSocketConfigurator;
import com.tqjc.system.core.util.PLCHttpsUtils;
import com.tqjc.system.core.util.SpringUtils;
import com.tqjc.system.system.entity.SysAddDetailTaskEntity;
import com.tqjc.system.system.service.SysAddDetailTaskService;
import com.tqjc.system.system.util.SystemUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author 86195
 * @version 1.0
 * @description 监控大屏socket
 * @date 2023/5/3 15:53
 */
@ServerEndpoint(value = "/carTaskExecutionInfo",configurator = WebSocketConfigurator.class)
@Component("TaskExecutionSocketService")
@Slf4j
public class TaskExecutionWebSocketService {

    private static Map<String, Session> sessionMap = new HashMap<>();





    @OnOpen
    public void onOpen(Session session) throws Exception {
        String ip = (String) session.getUserProperties().get(GlobalConstant.STRING_IP);
        Session lastSession = sessionMap.get(ip);
        if(lastSession == null){

            SysAddDetailTaskService service = SpringUtils.getBean(SysAddDetailTaskService.class);
            //得到天车执行任务信息
            List<CarExecuteInfoBO> list = service.getCarExecuteInfo(LocalDateTime.now(), TaskStatusEnum.STATUS_DOING.getStatus());
            List<CarExecuteInfoVO> res = new ArrayList<>(4);
            for (CarInfoVOEnum value : CarInfoVOEnum.values()) {
                CarExecuteInfoVO carExecuteInfoVO = new CarExecuteInfoVO();
                carExecuteInfoVO.setCarName(value.getCarName());
                carExecuteInfoVO.setNo(value.getNo());
                Map<String, String> map = SystemUtils.Sys_carInfo.get(ConfigConstant.CONFIG_TYPE_CAR_BAK_SN);
                String sn = map.get(value.getCarName());
                Map<String,String> paramMap = new HashMap<>(2);
                paramMap.put(GlobalConstant.STRING_SN,sn);
                paramMap.put(GlobalConstant.STRING_LABEL,value.getModelLable());
                ResponseLabelDataBO responseLabelDataBO = PLCHttpsUtils.sendPost(RemoteURLConstant.URL_READBC, paramMap, ResponseLabelDataBO.class);
                Map<String, String> content = responseLabelDataBO != null? responseLabelDataBO.getContent(): null;
                if(content != null){
                    String currentVal = content.get("currentVal") != null ?
                            content.get("currentVal").toLowerCase() : null;
                    if(GlobalConstant.VISIT_MODEL_FLAG){
                        carExecuteInfoVO.setModelType("自动");
                    } else {
                        carExecuteInfoVO.setModelType("true".equals(currentVal) ? "自动":"手动");
                    }
                }
                if(CollectionUtil.isNotEmpty(list)){
                    list.forEach( e -> {
                        if(value.getCarName().equals(e.getCarName())){
                            //天车名称相同，设值
                            carExecuteInfoVO.setStatus(TaskStatusEnum.getDescByStatus(e.getStatus()));
                            carExecuteInfoVO.setMaterialName(e.getMaterialName());
                            carExecuteInfoVO.setTankCarNo(TankCarNoEnum.getDescByCarNo(e.getTankCarNo()));
                        }
                    });
                }

                res.add(carExecuteInfoVO);
            }
            sessionMap.put(ip,session);
            this.sendMessage(res,"操作成功",GlobalConstant.HTTPSTATUS_SUCCESS);

        }


    }


    @OnClose
    public void onClose(Session session){
        //连接关闭
        String ip = (String) session.getUserProperties().get(GlobalConstant.STRING_IP);
        sessionMap.remove(ip);
    }


    @OnError
    public void onError(Throwable error,Session session){
        //连接关闭
        String ip = (String) session.getUserProperties().get(GlobalConstant.STRING_IP);
        log.error("MonitorWebSocketService running error");
        sendMessage(buildMapMessage(null,"出现异常，请联系管理员","1"),ip);
        sessionMap.remove(ip);
        error.printStackTrace();
    }


    private Map buildMapMessage(Map data,String msg,String code){
        Map map = new HashMap();
        if(GlobalConstant.HTTPSTATUS_SUCCESS.equals(code)){
            map.put("data",data);
        }
        map.put("msg",msg);
        map.put("code",code);
        return map;
    }


    private Map buildListMessage(List data,String msg,String code){
        Map map = new HashMap();
        if(GlobalConstant.HTTPSTATUS_SUCCESS.equals(code)){
            map.put("data",data);
        }
        map.put("msg",msg);
        map.put("code",code);
        return map;
    }



    public void sendMessage(Map resMap,String ip) {
        try {
            Session session = sessionMap.get(ip);
            session.getBasicRemote().sendText(JSON.toJSONString(resMap));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }




    public void sendMessage(Map resMap) {

        Map<String,Session> sessionMap = this.sessionMap;

        sessionMap.entrySet().forEach(e -> {
            try {
                e.getValue().getBasicRemote().sendText(JSON.toJSONString(resMap));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        });
    }

    public void sendMessage(List list, String msg, String code) {

        Map<String,Session> sessionMap = this.sessionMap;

        sessionMap.entrySet().forEach(e -> {
            try {
                e.getValue().getBasicRemote().sendText(JSON.toJSONString(this.buildListMessage(list,msg,code)));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        });
    }

    public  Map getSessionMap(){
        return this.sessionMap;
    }




}
